#include <linux/init.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/delay.h>
#include <linux/kthread.h>

// 线程函数
static int my_thread_fn(void *data)
{
    struct task_struct *current_task = current;

    printk(KERN_INFO "Thread is running. Going to sleep...\n");

    // 将当前线程设置为睡眠状态
    set_current_state(TASK_INTERRUPTIBLE);
    schedule();  // 放弃 CPU，进入睡眠状态

    // 被唤醒后继续执行
    printk(KERN_INFO "Thread is awake.\n");

    return 0;
}

static struct task_struct *my_thread;

static int __init my_module_init(void)
{
    // 创建内核线程
    my_thread = kthread_create(my_thread_fn, NULL, "my_thread");
    if (IS_ERR(my_thread)) {
        printk(KERN_ERR "Failed to create kernel thread.\n");
        return PTR_ERR(my_thread);
    }

    // 启动线程
    wake_up_process(my_thread);

    // 模拟主线程的工作
    printk(KERN_INFO "Main thread is running. Simulating work...\n");
    msleep(3000);  // 等待 3 秒

    // 唤醒线程
    printk(KERN_INFO "Main thread is waking up the sleeping thread.\n");
    wake_up_process(my_thread);

    return 0;
}

static void __exit my_module_exit(void)
{
    // 停止线程
    if (my_thread) {
        kthread_stop(my_thread);
        printk(KERN_INFO "Kernel thread stopped.\n");
    }
}

module_init(my_module_init);
module_exit(my_module_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple module to demonstrate wake_up_process.");